﻿using Business;
using MB.Orm.DB;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.OleDb;
using System.IO;
using Business.Service;


namespace MvcAppWeb.Controllers
{
    public class BaseDataController : Controller
    {
        //
        // GET: /BaseData/

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult UserList()
        {
            var retData = new object();
            NewCommon nc = new NewCommon();
            retData = nc.GetUserList().ToList();
            return Json(retData);
        }
        /// <summary>
        /// 获取全部模块
        /// </summary>
        /// <returns></returns>
        public JsonResult GetOAFileModularList()
        {
            string defaultValue = Request["defaultValue"].ToString();
            var retData = new object();
            BFileManage bm = new BFileManage();
            retData = bm.GetFileModularInfoByDropDownList(defaultValue).ToList();
            return Json(retData);
        }
        /// <summary>
        /// 获取全部系统
        /// </summary>
        /// <returns></returns>
        public JsonResult GetOAFileSystemList()
        {
            string defaultValue = Request["defaultValue"].ToString();
            var retData = new object();
            BFileManage bm = new BFileManage();
            retData = bm.GetFileSystemInfoByDropDownList(defaultValue).ToList();
            return Json(retData);
        }

        public string ImportFile(HttpPostedFileBase file, out DataTable ImportTable, out string ImportString)
        {
            string sjson = string.Empty;
            ImportTable = new DataTable();
            ImportString = string.Empty;

            string FileName;
            string savePath;
            if (file == null || file.ContentLength <= 0)
            {
                sjson = "{success:false,msg:'文件不能为空'}";
                return sjson;
            }
            string filename = Path.GetFileName(file.FileName);
            int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
            string fileEx = Path.GetExtension(filename);//获取上传文件的扩展名
            string NoFileName = Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
            int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
            string FileType = ".xls,.xlsx,.txt";//定义上传文件的类型字符串

            FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
            if (!FileType.Contains(fileEx))
            {
                sjson = "{success:false,msg:'文件类型不对，只能导入xls和xlsx或者txt格式的文件'}";
                return sjson;
            }
            if (filesize >= Maxsize)
            {
                sjson = "{success:false,msg:'上传文件超过4M，不能上传'}";
                return sjson;
            }
            string path = AppDomain.CurrentDomain.BaseDirectory + "upload/";
            savePath = Path.Combine(path, FileName);
            file.SaveAs(savePath);

            if (fileEx == ".txt")
            {
                StreamReader sr = new StreamReader(savePath, System.Text.Encoding.Default);
                ImportString = sr.ReadToEnd();
                ImportString = ImportString.Replace("\r\n", "").Replace("\n", "");
                sr.Close();
                return sjson;
            }
            string strConn;
            strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + savePath + ";" + "Extended Properties=Excel 12.0";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable sheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { null, null, null, "Table" });
            string[] sheet = new string[sheetName.Rows.Count];
            for (int i = 0, j = sheetName.Rows.Count; i < j; i++)
            {
                sheet[i] = sheetName.Rows[i]["TABLE_NAME"].ToString();
            }
            OleDbDataAdapter myCommand = new OleDbDataAdapter(string.Format("select * from [{0}]", sheet[0]), strConn);
            DataSet myDataSet = new DataSet();
            try
            {
                myCommand.Fill(myDataSet, "ExcelInfo");
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
                return sjson;
            }
            ImportTable = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
            return sjson;
        }


        /// <summary>
        /// 文件系统专用导入方法
        /// </summary>
        /// <param name="file"></param>
        /// <param name="ImportTable"></param>
        /// <param name="ImportString"></param>
        /// <returns></returns>
        public string OAImportFile(HttpPostedFileBase file, string url, out string importUrl, out string fileFormat, out string imfileName)
        {
            string sjson = string.Empty;
            importUrl = string.Empty;
            fileFormat = string.Empty;
            imfileName = string.Empty;
            string FileName = string.Empty; ;
            if (file == null || file.ContentLength <= 0)
            {
                sjson = "{success:false,msg:'文件不能为空'}";
                return sjson;
            }
            string filename = Path.GetFileName(file.FileName);
            int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
            string fileEx = Path.GetExtension(filename);//获取上传文件的扩展名
            string NoFileName = Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
            int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
            string FileType = ".xls,.xlsx,.txt.jpg.jpeg.gif.png.vsdx.docx.JPG.JPEG.PND.GIF";//定义上传文件的类型字符串

            FileName = NoFileName + fileEx;
            imfileName = FileName;
            fileFormat = fileEx;
            if (!FileType.Contains(fileEx))
            {
                sjson = "{success:false,msg:'文件类型不对，只能导入.xls,.xlsx,.txt.jpg.jpeg.gif.png.vsdx.docx的文件'}";
                return sjson;
            }
            if (filesize >= Maxsize)
            {
                sjson = "{success:false,msg:'上传文件超过4M，不能上传'}";
                return sjson;
            }

            string path = AppDomain.CurrentDomain.BaseDirectory + url;
            importUrl = url +"/"+ FileName;
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Path.Combine(path));
            if (!dir.Exists)
            {
                dir.Create();
            }
            file.SaveAs(Path.Combine(path, FileName));


            return sjson;
        }


        public string NewTimeStamp(string strFileName)
        {
            //生成文件名: 当前年月日小时分钟秒+ 随机数
            Random rd = new Random(int.Parse(DateTime.Now.ToString("MMddhhmmss")));
            strFileName += DateTime.Now.ToString("yyyyMMdd")
                + DateTime.Now.Hour
                + DateTime.Now.Minute
                + DateTime.Now.Second
                + rd.Next(999999).ToString()
                + ".xls";
            return strFileName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var jsonResult = filterContext.Result as JsonResult;
            if (jsonResult != null)
            {
                filterContext.Result = new JsonNetResult
                {
                    ContentEncoding = jsonResult.ContentEncoding,
                    ContentType = jsonResult.ContentType,
                    Data = jsonResult.Data,
                    JsonRequestBehavior = jsonResult.JsonRequestBehavior
                };
            }
            base.OnActionExecuted(filterContext);
        }
    }
}
